package com.zhouyu.gamecommunity.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Service
@Slf4j
@ServerEndpoint("/websocket/{id}")
public class WebSocketServer {
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;
    private String id;

    @OnOpen
    public void onOpen(Session session, @PathParam("id")String id) {
        this.session = session;
        webSocketSet.add(this);
        this.id = id;
        try {
            sendMessage("ok");
            log.info("连接的id为" + id);
        }catch (Exception e){
            log.info("websocket连接失败");
        }
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("释放的id为" + id);
    }
    @OnMessage
    public void onMessage(String message,Session session) {
        log.info("收到来自窗口" + id + "的信息" + message);
        for (WebSocketServer item : webSocketSet) {
            try {
                String jsonObject = JSON.parseObject(message).toJSONString();
                item.sendMessage(jsonObject);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("发生错误");
        error.printStackTrace();
    }

    public static void sendInfo(String message,@PathParam("id")String id) throws IOException {
        log.info("推送消息到窗口" + id + "的信息" + message);
        for (WebSocketServer webSocketServer : webSocketSet) {
            if (webSocketServer.id.equals(id)) {
                webSocketServer.sendMessage(message);
            }
        }
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}
